package com.jianbo.proxy.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.smartboot.http.common.logging.Logger;
import org.smartboot.http.common.logging.LoggerFactory;

/**
 * 耗时统计模块
 */
public class TimeUse {

    private static Logger logger = LoggerFactory.getLogger(TimeUse.class);
 
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            TimeUse.start("main");
            Debug.sleep(100);
            TimeUse.end("main");

            TimeUse.start("test");
            Debug.sleep(100);
            TimeUse.end("test");
        }
        double second = TimeUse.getSecond("test");
        logger.info("test use time " + second);
        double second2 = TimeUse.getSecond("main");
        logger.info("main use time " + second2);
    }

    // 将原来的 HashMap 替换为线程安全的 ConcurrentHashMap
    private static Map<String, Integer> executeSizeMap = new ConcurrentHashMap<String, Integer>();

    public static double getSecond(String name) {
        Long use = timeUseMap.get(name);
        return Double.valueOf(use) / 1000;
    }

    public static double getMs(String name) {
        Long use = timeUseMap.get(name);
        return use;
    }

    public static void logMs(String name) {
        int size = executeSizeMap.get(name);
        String sizeStr = String.format("%5d", size);
        logger.info("【" + name + "】 执行次数 = " + sizeStr + " 消耗时间 " + getMs(name) + " 毫秒");
        clear(name);
    }

    public static void logMs2(String name) {
        int size = executeSizeMap.get(name);
        String sizeStr = String.format("%5d", size);
        Debug.info("【" + name + "】 执行次数 = " + sizeStr + " 消耗时间 " + getMs(name) + " 毫秒");
        clear(name);
    }

    public static String logMs() {
        String str = "";
        str += "------------- Time Use Print START -------------\n";
        for(String name : timeUseMap.keySet()) {
            int size = executeSizeMap.get(name);
            String sizeStr = String.format("%5d", size);
            str += "【" + name + "】 执行次数 = " + sizeStr + " 消耗时间 " + getMs(name) + " 毫秒\n";
        }
        str += "------------- Time Use Print END -------------\n";
        // Debug.info(logger, str);
        logger.info(str);
        clear();
        return str;
    }

    private static long diffMs(Date newTime, Date oldTime) {
        long diffTime = newTime.getTime() - oldTime.getTime();
        return diffTime;
    }

    // 修改 start 方法，使用原子操作
    public static void start(String string) {
        timeRecordMap.put(string, new Date());
        // 使用 computeIfAbsent 和 compute 方法来确保原子性
        executeSizeMap.compute(string, (key, oldValue) -> (oldValue == null) ? 1 : oldValue + 1);
    }
    
    // 同时也需要对 timeRecordMap 进行线程安全处理
    private static Map<String, Date> timeRecordMap = new ConcurrentHashMap<String, Date>();
    private static Map<String, Long> timeUseMap = new ConcurrentHashMap<String, Long>();
    
    // 修改 end 方法，确保原子性
    public static void end(String name) {
        Date lastRecord = timeRecordMap.get(name);
        if(lastRecord == null) {
            return;
        }
        Date now = new Date();
        long diff = diffMs(now, lastRecord);
        // 使用原子操作更新时间统计
        timeUseMap.compute(name, (key, oldValue) -> (oldValue == null) ? diff : oldValue + diff);
    }

    public static void clear() {
        timeRecordMap.clear();
        timeUseMap.clear();
        executeSizeMap.clear();
    }
    
    public static void clear(String title) {
        timeRecordMap.remove(title);
        timeUseMap.remove(title);
        executeSizeMap.remove(title);
	}
}